import React from "react";
import { useState, useEffect,useRef } from "react";
import { Table, Button, Modal, Switch } from "antd";
import UserForm from "../../../components/user-manage/UserForm";
import {
  DeleteOutlined,
  EditOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons";
import axios from "axios";

export default function UserList() {
  const { confirm } = Modal;
  const [dataSource, setdataSource] = useState([]);
  const [isAddVisible, setisAddVisible] = useState(false);
  const [regionList, setregionList] = useState([]);
  const [roleList, setroleList] = useState([]);
  const [isUpdateVisible, setisUpdateVisible] = useState(false)
  const [isUpdateDisabled, setisUpdateDisabled] = useState([])
  const addForm = useRef(null)
  const updateForm = useRef(null)

  useEffect(() => {
    axios.get("http://localhost:5000/users?_expand=role").then((res) => {
      setdataSource(res.data);
    });
  }, []);
  useEffect(() => {
    axios.get("http://localhost:5000/regions").then((res) => {
      const list = res.data;
      setregionList(list);
    });
  }, []);

  useEffect(() => {
    axios.get("http://localhost:5000/roles").then((res) => {
      const list = res.data;
      setroleList(list);
    });
  }, []);

  



  const confirmMethod = (item) => {
    confirm({
      title: "你确定要删除?",
      icon: <ExclamationCircleOutlined />,
      onOk() {
        deleteMethod(item);
      },
      onCancel() {},
    });
  };
  const deleteMethod = (item) => {
    setdataSource(dataSource.filter(data=>data.id!==item.id))
    axios.delete(`http://localhost:5000/users/${item.id}`)
  };

  const addFormOK = () => {
    addForm.current.validateFields().then(value => {
        // console.log(value)

        setisAddVisible(false)

        addForm.current.resetFields()
        //post到后端，生成id，再设置 datasource, 方便后面的删除和更新
        axios.post(`http://localhost:5000/users`, {
            ...value,
            "roleState": true,
            "default": false,
        }).then(res=>{
            // console.log(res.data)
            setdataSource([...dataSource,{
                ...res.data,
                role:roleList.filter(item=>item.id===value.roleId)[0]
            }])
        })
    }).catch(err => {
        console.log(err)
    })
}
const updateFormOK = ()=>{
  
  
}
  const handleChange = (item)=>{
    item.roleState=!item.roleState
    setdataSource([...dataSource])
    axios.patch(`http://localhost:5000/users/${item.id}`,{
      roleState:item.roleState
    })
  }
  const handleUpdate = (item)=>{
    setTimeout(()=>{
        setisUpdateVisible(true)
        if(item.roleId===1){
            //禁用
            setisUpdateDisabled(true)
        }else{
            //取消禁用
            setisUpdateDisabled(false)
        }
        updateForm.current.setFieldsValue(item)
    },0)
}

  const columns = [
    {
      title: "区域",
      dataIndex: "region",
      render: (region) => {
        return <b>{region ? region : "全球"}</b>;
      },
    },
    {
      title: "角色名称",
      dataIndex: "role",
      render: (role) => {
        return role.roleName;
      },
    },
    {
      title: "用户名",
      dataIndex: "username",
    },
    {
      title: "用户状态",
      dataIndex: "roleState",
      render: (roleState, item) => {
        return <Switch checked={roleState} disabled={item.default} onChange={()=>handleChange(item)}></Switch>;
      },
    },
    {
      title: "操作",
      render: (item) => {
        return (
          <div>
            <Button
              disabled={item.default}
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => confirmMethod(item)}
            />

            <Button
              disabled={item.default}
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={()=>{
              
              handleUpdate(item)
              }}
            />
          </div>
        );
      },
    },
  ];
  return (
    <div>
      <Button
        type="primary"
        onClick={() => {
          setisAddVisible(true);
        }}
      >
        添加用户
      </Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 5,
        }}
        rowKey={(item) => item.id}
      />
      ;
      <Modal
        visible={isAddVisible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisAddVisible(false);
        }}
        onOk={() => {addFormOK()}}
      >
        <UserForm regionList={regionList} roleList={roleList} ref={addForm}></UserForm>
      </Modal>
      <Modal
        visible={isUpdateVisible}
        title="更新用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => {
          setisUpdateVisible(false);
          setisUpdateDisabled(!isUpdateDisabled)
        }}
        onOk={() => {updateFormOK()}}
      >
        <UserForm regionList={regionList} roleList={roleList} ref={updateForm} isUpdateDisabled={isUpdateDisabled}></UserForm>
      </Modal>
    </div>
  );
}
